package com.leetcode;

import java.util.Deque;
import java.util.LinkedList;
import java.util.Stack;

public class 找出最长的括号 {

    /**
     * ))()()(
     *
     * @param str
     * @return
     */
    public static int maxLength(String str) {
        if (str.length() == 0) return 0;
        char[] chars = str.toCharArray();
        int maxLenth = 0;
        int len = chars.length;
        LinkedList<Character> stack = new LinkedList<Character>();
        for (int i = 0; i < len; i++) {
            char c = str.charAt(i);
            if (stack.size() == 0 && c == '(') {
                stack.push(c);
            } else if (stack.size() != 0) {
                Character peek = stack.peek();
                if (peek == c) {
                    maxLenth = Math.max(maxLenth, stack.size());
                    stack.clear();
                    stack.push(c);
                } else {
                    stack.push(c);
                }
            }
        }
        return stack.size() > maxLenth ? stack.size() : maxLenth;
    }

    public static int longestValidParentheses(String s) {
        int maxans = 0;
        Deque<Integer> stack = new LinkedList<Integer>();
        stack.push(-1);
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '(') {
                stack.push(i);
            } else {
                stack.pop();
                if (stack.isEmpty()) {
                    stack.push(i);
                } else {
                    maxans = Math.max(maxans, i - stack.peek());
                }
            }
        }
        return maxans;
    }

    public static void main(String[] args) {
//        System.out.println(maxLength(")()()()()"));
//        System.out.println(maxLength("())((()()"));
//        System.out.println(maxLength("())"));
        System.out.println(longestValidParentheses("())"));
    }

}

/**
 *
 */
class Solution {

}
